<?php
/**
 * Created by PhpStorm.
 * User: jiangxiaobo
 * Date: 2019/11/11 0011
 * Time: 19:01
 */
namespace bootstrap;

use bootstrap\lib\Request;
use bootstrap\lib\Response;
use routes\Web as WebRoute;

final class App
{
    static private function autoload($classname)
    {
        /**
         * \app::a(); => $classname=app
         * \app\index::a(); => $classname=app\index
         */
        $names = explode("\\", $classname);

        $filename = ROOT_PATH.implode(DS, $names).EXT;

        include $filename;
    }

    static public function main()
    {
        // 环境常量
        define('IS_CLI', PHP_SAPI == 'cli' ? true : false);
        define('IS_WIN', strpos(PHP_OS, 'WIN') !== false);

        define('EXT', '.php');
        define('DS', DIRECTORY_SEPARATOR);
        define('ROOT_PATH', dirname(dirname(realpath($_SERVER['SCRIPT_FILENAME']))) . DS);

        defined('ENV_PREFIX') or define('ENV_PREFIX', 'PHP_'); // 环境变量的配置前缀

        // 注册AUTOLOAD方法
        spl_autoload_register(__CLASS__."::autoload");

        if(IS_CLI) {
            echo "cli";
        } else if(Request::getInstance()->isAjax()) {
            echo json_encode(['error' => 1]);
        } else {
            WebRoute::getInstance()->trigger();
        }

        return Response::getInstance();
    }
}
